/**
 author: chengzheng
 date: 2017/12/26
 email: 13120207061@163.com
 */

//https://www.sitepoint.com/making-http-requests-in-node-js/
var request = require('request');
var logger = require("../logger");

let retryLimit = 10;

/**
 * @desc 封装过的基础http请求
 * @return Promise
 */
function http(option) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    let interval = null;
    let retry = 0;
    let inst = null;
    let timeout = 3000;
    if (!!option.retryLimit) {
        retryLimit = option.retryLimit;
    }

    logger.info(`plain http request invoke with url: ${option.url}`);
    return new Promise((resolve, reject) => {
        let cb = function (err, resp, httpBody) {
            if (err) {
                logger.warn(`base http method error and retry, error message: ${err.toString()}`);
                inst = request(option, cb);
            }
            else {
                logger.trace(`plain http request finish: ${option.url}`);
                resolve(httpBody);
                clearInterval(interval);
            }
        };

        inst = request(option, cb);
        interval = setInterval(() => {
            inst.abort();

            if (retry > retryLimit) {
                logger.error(`plain http request failed, url: ${option.url}`);
                return;
            }
            retry++;
            logger.debug(`plain http retry: ${retry}`);
            inst = request(option, cb);
        }, timeout);
    });
}

module.exports = http;